// 这个文件专门用来存放关于图片的所有接口
const Router = require('koa-router');
const upload_image = new Router();
// 拿到前端传过来的数据 koa-bodyparse
const bodyparse = require("koa-bodyparser");
let multer = require('koa-multer');
let path = require('path');
// 调用下面这个中间件，就可以拿到前端post过来的数据
upload_image.use(bodyparse());

let storage = multer.diskStorage({
    destination: path.resolve("assets/images/upload"),
    filename: (ctx, file, cb) => {
        let num = file.originalname.lastIndexOf('.');
        let suffix = file.originalname.substring(num);
        cb(null, Date.now() + suffix);//写入自己的服务器文件夹
    },
});
let fileFileter = (ctx, file, cb) => {
    // 过滤上传的后缀为txt的文件
    let num = file.originalname.lastIndexOf(".");
    let suffix = file.originalname.substring(num);
    if (!suffix in [".jpg", ".png", ".jpeg", ".gif"]) {
        cb(null, falese);
    } else {
        cb(null, true);
    };

};
let upload = multer({ storage: storage, fileFilter: fileFileter });

upload_image.post('/', upload.single("file"), async (ctx) => {
    // console.log(ctx.request.files);
    console.log(ctx.request.files.file.newFilename);
    const filePath = ctx.request.files.file.newFilename;//接收到的文件名字
    // 注意这的文件路径为/images/upload/图片名字
    // 因为app.js 里面我们配置的静态资源路径为aeests,所以访问时候会自动忽略掉assets
    console.log(`http://localhost:5050/images/upload/${filePath}`);
    ctx.body = {
        code: 200,
        message: "上传成功",
        data: {
            url: `/images/upload/${filePath}`,
        },
    }; // 返回上传成功信息和图片访问路径
})



module.exports = upload_image;